package com.gzkit.jijianmeeting.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gzkit.jijianmeeting.common.PageInfos;
import com.gzkit.jijianmeeting.common.util.MD5Util;
import com.gzkit.jijianmeeting.common.util.PageUtils;
import com.gzkit.jijianmeeting.dao.UserMapper;
import com.gzkit.jijianmeeting.entity.UserEntity;
import com.gzkit.jijianmeeting.service.UserService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author xielong
 * @Title:
 * @Description:
 * @date 2018/1/22 0022
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource(name = "userMapper")
    private UserMapper userMapper;

    @Override
    public PageInfos<UserEntity> getUserEntities(int page, int rows) {
        PageHelper.startPage(page, rows);
        List list=userMapper.getList();
        PageInfos pageInfos=new PageInfos();
        pageInfos.setData(list);
        PageInfo<UserEntity> userPageInfo = new PageInfo<>(list);
        return PageUtils.convert(userPageInfo);
    }

    @Override
    public boolean login(String account, String password, HttpServletRequest request) {
        Example example = new Example(UserEntity.class);
        example.createCriteria()
                .andEqualTo("account", account);
       try{
        UserEntity userEntity = userMapper.selectOneByExample(example);
        if (userEntity != null) {
            String pw = MD5Util.getMD5(password, "", 0);
            if (pw.equals(userEntity.getPassword())) {
                request.getSession().setAttribute("user",userEntity);
                return true;
            }
        }
       }catch(Exception e){
           e.printStackTrace();
           throw  new RuntimeException(e);
       }
        return false;
    }

    @Override
    public boolean isExistUser(String account) {
        Example example = new Example(UserEntity.class);
        example.createCriteria()
                .andEqualTo("account", account);
        try{
            UserEntity userEntity = userMapper.selectOneByExample(example);
            if (userEntity != null) {
               return true;
            }
        }catch(Exception e){
            e.printStackTrace();
            throw  new RuntimeException(e);
        }
        return false;
    }
}
